<?php

/**
 * 公告管理
 */

namespace app\admin\controller;

use app\common\model\AnnouncementModel;
use think\facade\Request;

class AnnouncementController extends BaseController {
    public function index() {
        return $this->fetch();
    }

    public function add() {
        return $this->fetch();
    }

    public function edit() {
        $notice = AnnouncementModel::where(['id' => Request::param('id')])->find();
        $this->assign('notice', $notice);
        return $this->fetch();
    }

    public function getList() {
        $title = Request::param("title");
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $where = [];
        if ($title) {
            $where[] = ['title', 'like', "%{$title}%"];
        }

        $count = AnnouncementModel::where($where)->count("id");

        if ($count > 0) {
            $notice = AnnouncementModel::with(['admin' => function ($query) {
                $query->field('id,name');
            }])->field('content', true)
                ->where($where)
                ->order("id desc")
                ->limit(($page - 1) * $limit, $limit)->select();

            return json(["code" => 0, "msg" => "", "data" => $notice, "count" => $count]);
        }

        return self::bulidFail('暂无数据');
    }

    public function add_post() {
        $params              = Request::param();
        $notice              = new AnnouncementModel($params);
        $notice->manager_id  = $this->userinfo->id;
        $notice->create_time = date("Y-m-d H:i:s");
        if ($notice->save()) {
            // 记录日志
            $log_content = "添加公告，公告ID：{$notice->id}，标题：{$notice->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess([], '添加成功');
        }
        return self::bulidFail();
    }

    public function edit_post() {
        $notice = AnnouncementModel::where(['id' => Request::param('id')])->find();
        if (!$notice) {
            return self::bulidFail('数据异常');
        }
        $notice->title   = Request::param('title');
        $notice->content = Request::param('content');
        if ($notice->save()) {
            // 记录日志
            $log_content = "编辑公告，公告ID：{$notice->id}，标题：{$notice->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function del_post() {
        $id           = Request::param('id');
        $announcement_model = AnnouncementModel::get($id);
        if (!$announcement_model) {
            return self::bulidFail('未查询到相关公告');
        }

        if (AnnouncementModel::where(['id' => $id])->delete()) {
            // 记录日志
            $log_content = "删除公告，公告ID：{$announcement_model->id}，标题：{$announcement_model->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

}
